package cn.demomaster.quickrouter.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;

import androidx.annotation.MenuRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.demomaster.quickcompat.util.DisplayUtil;
import com.demomaster.quickcompat.util.StatusBarUtil;
import com.demomaster.quickcompat.view.menu.NavMenu;

import java.lang.ref.WeakReference;

import cn.demomaster.quickrouter.R;
import cn.demomaster.quickrouter.actionbar.ActionBarTool;
import cn.demomaster.quickrouter.fragment.QuickFragment;
import cn.demomaster.quickrouter.fragment.QuickPage;
import cn.demomaster.quickrouter.fragment.ViewLifecycle;
import cn.demomaster.quickrouter.manager.QuickFragmentHelper;

public abstract class QuickActivity extends AppCompatActivity implements QuickPage {
    public static String TAG = QuickActivity.class.getName();
    public QuickActivity mContext;

    public QuickActivity getContext() {
        return mContext;
    }

    /**
     * 页面返回
     */
    @Override
    public void onClickBack() {
        finish();
    }

    /**
     * 是否支持拖动页面手势
     *
     * @return
     */
    @Override
    public boolean canDrag() {
        return false;
    }

    /**
     * 页面拖动触发关闭页面方法
     */
    @Override
    public void onDragFinish() {
        finish();
    }

    ///是否使用自定义导航
    @Override
    public boolean isUseActionBarLayout() {
        return true;
    }

    //是否透明化状态栏
    @Override
    public boolean isTransparencyBar() {
        return true;
    }

    /**
     * 设置自定义导航栏
     *
     * @return
     */
    public View getHeaderlayout() {
        return View.inflate(this, R.layout.qd_activity_actionbar_common, null);
    }

    private ActionBarTool actionBarTool;

    //获取自定义导航
    public ActionBarTool getActionBarTool() {
        if (actionBarTool == null) {
            actionBarTool = new ActionBarTool(this);
        }
        return actionBarTool;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mContext = this;
        initMenu();
        actionBarTool = null;
        fragmentHelper = null;
        if (isTransparencyBar()) {
            StatusBarUtil.transparencyBar(new WeakReference<>(mContext));
        }
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate-" + getClass().getSimpleName() + "-" + hashCode());

        /*if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }*/
        //setSupportActionBar(new QuickToolbar(this));
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        setContentView(view);
    }

    @Override
    public void setContentView(View view) {
        View view1 = decorateView(view);
        super.setContentView(view1);
        //bind在setContentView之后 ButterKnife.bind(this);
        initContentView();
        initOptionsMenu(navigationMenu);
    }

    /**
     * 对传递过来的view 再次包装
     *
     * @param view
     * @return
     */
    public View decorateView(View view) {
        if (isUseActionBarLayout()) {//是否使用自定义导航栏
            actionBarTool = getActionBarTool();
            //actionBarTool.
            ActionBarTool.Builder builder = getActivityLayoutBuilder(mContext);
            builder.setContentView(view);
            View mActionBarLayout = getActionBarTool().genarateView(builder);
            getActionBarTool().setLeftOnClickListener(v -> finish());
            return mActionBarLayout;
        } else {
            return view;
        }
    }

    /**
     * 自定义导航构建者
     *
     * @param mContext
     * @return
     */
    public ActionBarTool.Builder getActivityLayoutBuilder(Activity mContext) {
        ActionBarTool.Builder builder = new ActionBarTool.Builder(mContext)
                .setActionBarView(getHeaderlayout())
                .setHasStatusBar(true)
                .setStatusHeight(DisplayUtil.getStatusBarHeight(mContext))
                .setContentViewPaddingTop(ActionBarTool.PaddingWith.none)
                .setMixStatusActionBar(true);
        return builder;
    }

    public void initContentView() {

    }

    NavMenu navigationMenu;

    /**
     * 此处可自定义返回menu配置文件id
     *
     * @return
     */
    @SuppressLint("RestrictedApi")
    public @MenuRes int getMenuRes() {
        return -1;
    }

    private void initMenu() {
        if (getMenuRes() != -1) {
            navigationMenu = new NavMenu(mContext);
            getMenuInflater().inflate(getMenuRes(), navigationMenu);
        }
    }

    public void initOptionsMenu(Menu menu) {

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //Log.i(TAG,"onNewIntent-"+getClass().getSimpleName()+"-"+hashCode());
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        Log.i(TAG, "onSaveInstanceState-" + getClass().getSimpleName() + "-" + hashCode());
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.i(TAG, "onRestoreInstanceState-" + getClass().getSimpleName() + "-" + hashCode());
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "onStart-" + getClass().getSimpleName() + "-" + hashCode());

////        处理虚拟按键
//        // 获取屏幕高度
//        Display display = getWindowManager().getDefaultDisplay();
//        Point size = new Point();
//        display.getSize(size);
//        int screenHeight = size.y;
//        // 获取底部导航栏高度
//        int navigationBarHeight = QMUIDisplayHelper.getNavMenuHeight(mContext);
//
//        // 计算可用高度
//        int availableHeight = screenHeight - navigationBarHeight;
//
//        // 调整布局高度
        //View contentLayout = findViewById(android.R.id.content);
        //ViewGroup.LayoutParams params = contentLayout.getLayoutParams();
        //params.height = QMUIDisplayHelper.getNavMenuHeight(mContext);
        //contentLayout.setLayoutParams(params);

        //findViewById(R.id.sliding_layout).setPadding(0, 0, 0, QMUIDisplayHelper.getNavMenuHeight(mContext));//设置底部导航栏高度
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume-" + getClass().getSimpleName() + "-" + hashCode());
    }

    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        if (actionBarTool != null) {
            actionBarTool.setTitle(title);
        }
    }

    @Override
    public void finish() {
        //QdLog.e("isMainThread:"+QuickThread.isMainThread());
        //QuickRleaser.release(this);
        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (actionBarTool != null) {
            actionBarTool.onRelease(this);
        }
        Log.i(TAG, "onDestroy-" + getClass().getSimpleName() + "-" + hashCode());
//        if (EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().unregister(this);
//        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Log.i(TAG, "onLowMemory-" + getClass().getSimpleName() + "-" + hashCode());
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        Log.i(TAG, "onTrimMemory- level:" + level + getClass().getSimpleName() + "-" + hashCode());
    }

    public int getContentViewId() {
        //Log.i(TAG,"getDelegate()"+getDelegate()+",android.R.id.content="+android.R.id.content);
        return android.R.id.content;//R.id.qd_fragment_content_view;
    }

    public QuickFragmentHelper fragmentHelper;

    public QuickFragmentHelper getFragmentHelper() {
        if (fragmentHelper == null) {
            fragmentHelper = new QuickFragmentHelper(mContext, getContentViewId());
        }
        return fragmentHelper;
    }

    public void startFragment(QuickFragment fragment, Integer containerViewId, Intent intent) {
        if (containerViewId == null) {
            containerViewId = android.R.id.content;
        }
        //getFragmentHelper().navigate(mContext,fragment, parentId,intent);
        QuickFragmentHelper.Builder builder = new QuickFragmentHelper.Builder(mContext, fragment, getFragmentHelper());
        builder.setIntent(intent)
                .setContainerViewId(containerViewId)
                .navigation();
    }

    public void startFragmentForResult(QuickFragment fragment, Integer containerViewId, Intent intent, ViewLifecycle viewLifecycle, int requestCode) {
        if (containerViewId == null) {
            containerViewId = android.R.id.content;
        }
        //getFragmentHelper().navigate(mContext,fragment, parentId,intent);
        QuickFragmentHelper.Builder builder = new QuickFragmentHelper.Builder(mContext, fragment, getFragmentHelper());
        builder.setIntent(intent)
                .setContainerViewId(containerViewId)
                .setRequestCode(requestCode)
                .navigation(viewLifecycle,true, requestCode);
    }

    public void startActivity(Class<?> clazz) {
        startActivity(clazz, null);
    }

    public void startActivity(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        mContext.overridePendingTransition(R.anim.translate_from_right_to_left_enter, R.anim.anim_null);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Log.i(TAG, "onBackPressed");
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        //QdLog.d("onKeyUp=" + keyCode + ",event=" + event);
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //QdLog.d("keyCode1=" + keyCode + ",event=" + event);
        if (fragmentHelper != null) {
            if (fragmentHelper.onKeyDown(mContext, keyCode, event)) {
                //QdLog.d("点击事件已被fragment"+getClass().getName()+"消费 keyCode=" + keyCode + ",event=" + event);
                return true;
            }
        }
        //QdLog.d( "keyCode2="+keyCode);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getApplicationInfo().targetSdkVersion
                    >= Build.VERSION_CODES.ECLAIR) {
                event.startTracking();
                //QdLog.d( "keyCode3");
            } else {
                onBackPressed();
                //QdLog.d( "keyCode4");
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean isDestroyed() {
        return isFinishing() || super.isDestroyed(); //;
    }

    /**
     * 判断Activity是否Destroy
     *
     * @param mActivity
     * @return true:已销毁
     */
    public static boolean isDestroyed(Activity mActivity) {
        return mActivity == null ||
                mActivity.isFinishing() ||
                (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed());
    }

}
